
using Consul;
using ERP.Common;
using ERP.Common.Extensions;
using Finance.Api.Write.Extensions;
using Finance.Domain;
using Finance.Infrastructure;
using Microsoft.OpenApi.Models;
using NLog.Web;
using Serilog;
using Serilog.Events;
using Serilog.Sinks.Elasticsearch;
using SqlSugar;

var builder = WebApplication.CreateBuilder(args);

//注册consul
static void RegisterConsul()
{
    try
    {
        var consulClient = new ConsulClient(p => {
            p.Address = new Uri("http://47.99.42.133:8500");//主机ip:8500
        });
        // 2. 确保健康检查端点可访问
        var httpCheck = new AgentServiceCheck()
        {
            DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),
            Interval = TimeSpan.FromSeconds(10),
            HTTP = "http://39.96.193.163:8540/WeatherForecast", // 确认此端口服务是否运行
            Timeout = TimeSpan.FromSeconds(5)
        };
        // 3. 添加标签方便识别
        var registration = new AgentServiceRegistration()
        {
            Checks = new[] { httpCheck },
            ID = $"wmsworkwrite-{Guid.NewGuid()}", // 更易读的ID
            Name = "wmsworkwrite",                // 必须小写
            Address = "39.96.193.163",                   // 纯IP正确
            Port =8540,                               // 端口与健康检查一致
            Tags = new[] { "dotnet-service" }           // 添加标签
        };

        // 4. 添加错误处理
        var result = consulClient.Agent.ServiceRegister(registration).Result;
        Console.WriteLine($"服务注册成功! Status: {result.StatusCode}");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Consul注册失败: {ex.Message}");
    }
}



///ELK日志
var configuration = builder.Configuration;
// 配置Serilog
var elaUri = configuration["ELK:ElaticSearchUrl"];
var userName = configuration["ELK:UserName"];
var password = configuration["ELK:Password"];
Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Information()
    .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
    .Enrich.FromLogContext()
    .Enrich.WithMachineName()
    .Enrich.WithThreadId()
    .Enrich.WithProcessId()
    .WriteTo.Console(new Serilog.Formatting.Compact.CompactJsonFormatter())
    .WriteTo.File("logs/sunworkwrite-.txt",
        rollingInterval: RollingInterval.Day,
        outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}")
    .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri(elaUri))
    {
        IndexFormat = "sunworkwrite-logs-{0:yyyy.MM.dd}",
        AutoRegisterTemplate = true,
        AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv7,
        ModifyConnectionSettings = conn => conn.BasicAuthentication(userName, password),
        BufferBaseFilename = "./logs/serilog-buffer",
        Period = TimeSpan.FromSeconds(2)
    })
    .CreateLogger();

builder.Host.UseSerilog();

// Add services to the container.

builder.Services.AddControllers();

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(x =>
{
    //jwt��Ȩ��swagger�е�Ӧ��
    //x.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
    //{
    //    Description = "���¿�����������ͷ����Ҫ����Jwt��ȨToken��Bearer Token",
    //    Name = "Authorization",
    //    In = ParameterLocation.Header,
    //    Type = SecuritySchemeType.ApiKey,
    //    BearerFormat = "JWT",
    //    Scheme = "Bearer"
    //});
    x.AddSecurityRequirement(new OpenApiSecurityRequirement
        {
            {
                new OpenApiSecurityScheme
                {
                    Reference = new OpenApiReference
                    {
                        Type = ReferenceType.SecurityScheme,
                        Id = "Bearer"
                    }
                },
                new string[] { }
            }
        });

    var path = Path.Combine(AppContext.BaseDirectory, "Finance.Api.Write.xml");
    x.IncludeXmlComments(path, true);
    x.AddServer(new OpenApiServer()
    {
        Url = "/wmsworkwrite",
        Description = "Kong Gateway"
    });
});
builder.Services.AddServices(builder);
builder.Services.ADDJWT(builder);
builder.Host.UseNLog();
builder.Services.AddScoped(typeof(SqlsugarDb<>));

builder.Services.AddControllers(x => x.Filters.Add<GlobalExceptionFilter>());
var app = builder.Build();
//consul注册
RegisterConsul();
app.UseCors(x => x.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());


app.UseSwagger();
    app.UseSwaggerUI();


app.UseAuthorization();

app.MapControllers();

app.Run();
